<template>
  <div class="register-container">
    <h1>用户注册</h1>
    <el-form ref="form" :model="user" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="user.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="user.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
      <router-link to="/login">已有账号？去登录</router-link>
    </el-form>
  </div>
</template>

<script>
import { register } from '@/api/user.js'

export default {
  name: 'Register',
  data() {
    return {
      user: {
        username: '',
        gender: '',
        phone: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          try {
            await register(this.user)
            this.$router.push('/login')
          } catch (error) {
            if (error.response && error.response.status === 409) {
              this.$message.error('用户名已存在')
            } else {
              this.$message.error('注册失败')
            }
          }
        } else {
          console.log('form validation failed')
        }
      })
    },
    resetForm() {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>
.register-container {
  padding: 20px;
}
</style>
